package com.bootdo.lgs.scheduled;

import com.bootdo.common.exception.ParmException;
import com.bootdo.common.model.BdConstant;
import com.bootdo.lgs.lgsInterfaces.blc.service.BlcService;
import com.bootdo.lgs.lgsInterfaces.jzy.JzyLogisticsService;
import com.bootdo.lgs.order.dao.OrderMapper;
import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.orderbind.model.OrderBindUpdate;
import com.bootdo.lgs.orderbind.service.OrderBindService;
import com.bootdo.system.domain.UserDO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description:
 * 绑定单号失败时的2种情况
 * --下单到物流公司成功但是、绑定单号失败的订单进行补偿、从缓存获取订单号绑定物流单号
 * 下单到物流公司失败、再次下单到物流公司并绑定单号
 * @Author: guoyouwei
 * @Date: 2019/7/16 8:30
*/
@Profile(value = "pro")
@Component
public class ReLgsFailOrder {

    private static final Logger logger = LoggerFactory.getLogger(ReLgsFailOrder.class);

    private final static long TIME_INTERVAL= 1 * 60 * 60 * 1000;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BlcService blcService;

    @Autowired
    private OrderBindService orderBindService;

    //@Scheduled(cron = "0 0 0 * * ?")//每天凌晨执行一次
    @Scheduled(fixedDelay=TIME_INTERVAL) //每小时执行一次 补偿
    public void refreshLoginJob() {
        logger.info("====== 开始 查询自动绑单失败单号 =======");
        List<LgsOrder> lgsOrders = orderMapper.getFailLgsOrder();
        if(CollectionUtils.isEmpty(lgsOrders))
            return;
        Map<String, List<LgsOrder>> companyCdMap = lgsOrders.stream().collect(Collectors.groupingBy(LgsOrder::getLgs_company_cd));//按公司代码分组

        List<OrderBindUpdate> orderBindUpdateList = new ArrayList<>();
        for (Map.Entry<String, List<LgsOrder>> itemEntry : companyCdMap.entrySet()) {
            if("lgs_jcy".equals( itemEntry.getKey())){ //今朝阳
                List<LgsOrder> itemValue = itemEntry.getValue();
                for(LgsOrder item : itemValue){
                    //如果下单成功，不再处理
                    Object valueObj = null;
                    try {
                        valueObj = redisTemplate.opsForValue().get(BdConstant.LGS_ALREADY_SUCCESS_SAVE_ORDER_ID+item.getId());
                    } catch (Exception e) {
                        logger.warn("自动下单：从缓存中获取今朝阳已下单id失败。",e); //从缓存获取信息异常，不再处理
                        continue;
                    }
                    if(null==valueObj){//缓存中没有该订单的下单成功记录id，需再次下单
                        List<LgsOrder> saveOrders = new ArrayList<>();
                        saveOrders.add(item);
                        try {
                            logger.info("自动下单：下单："+saveOrders);
                            orderBindUpdateList.addAll(JzyLogisticsService.saveOrders(saveOrders));
                        } catch (Exception e) {
                            logger.warn("自动下单：下单今朝阳物流系统失败。"+saveOrders,e);
                        }
                    }else{
                        if(StringUtils.isNotBlank(valueObj.toString())){
                            OrderBindUpdate orderBindUpdate  = new OrderBindUpdate();
                            orderBindUpdate.setId(item.getId());
                            orderBindUpdate.setLgs_track_number(valueObj.toString());
                            orderBindUpdateList.add(orderBindUpdate);
                            logger.info("自动下单：今朝阳缓存中存在成功记录："+orderBindUpdate);
                        }
                    }
                }

            } else if( "lgs_blc".equals(itemEntry.getKey()) ) { //百路驰
                List<LgsOrder> itemValue = itemEntry.getValue();
                for(LgsOrder item : itemValue){
                    Object valueObj = null;
                    try {
                        valueObj = redisTemplate.opsForValue().get(BdConstant.LGS_ALREADY_SUCCESS_SAVE_ORDER_ID+item.getId());
                    } catch (Exception e) {
                        logger.warn("自动下单：百路驰从缓存中获取已下单id失败。",e); //从缓存获取信息异常，不再处理
                        continue;
                    }
                    if(null==valueObj){//缓存中没有该订单的下单成功记录id，需再次下单
                        try {
                            orderBindUpdateList.add( blcService.sendOrder(item) );
                        } catch (ParmException pe){
                            logger.info(pe.getMessage(),pe);
                        }catch (Exception e) {
                            logger.info("自动下单：百路驰下单失败:"+item,e);
                        }
                    }else{
                        if(StringUtils.isNotBlank(valueObj.toString())){
                            OrderBindUpdate orderBindUpdate  = new OrderBindUpdate();
                            orderBindUpdate.setId(item.getId());
                            orderBindUpdate.setLgs_track_number(valueObj.toString());
                            orderBindUpdateList.add(orderBindUpdate);
                            logger.info("自动下单：百路驰缓存中存在成功记录："+orderBindUpdate);
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(orderBindUpdateList)){//绑定单号
                UserDO userDO = new UserDO();
                userDO.setUserId(1l);
                orderBindService.batchUpdateLgsNumber(orderBindUpdateList, userDO);
            }
        }
        logger.info("======结束 自动绑单补偿 =======");
    }


}
